<!-- 批次-->
<template>
  <MainSlot v-loading="loading">
    <!-- <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template> -->
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :config="table_config" :tableThead="tableThead" :dataList="dataList" :loading="loading"
        @selection-change="selectionChange">
        <template v-slot:objectives="{ row }">
          <span v-show="row.batchId" class="pointer primary" @click="queryByConditionBatchInfo(row.batchId,'objectives')">点击查看</span>
        </template>
        <template v-slot:realities="{ row }">
          <span v-show="row.batchId" class="pointer primary" @click="queryByConditionBatchPond(row.batchId,'realities')">点击查看</span>
        </template>
        <template v-slot:facilityId="{ row }">
          {{ facilityObj[row.facilityId] }}
        </template>
        <template v-slot:status="{ row }">
          {{ row.status == 'COMPLETED' ? '已完成' : '未完成' }}
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size"  @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <!-- 生产批次 -->
      <AddEdit :title="'批次'" :parentId="parentId" :batchType="batchType" :facilityList="facilityList"
        :varietyList="varietyList" @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible"
        :data="formData">
      </AddEdit>
      <BatchInfo :title="'批次信息'" :dialogVisible="isViewBatchInfo" :batchInfoFlag="batchInfoFlag" :batchInfo="batchInfo" @closeDialog="closeDialog" />
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
// 添加批次
import AddEdit from './components/addEdit.vue';
// 批次信息
import BatchInfo from './components/batchInfo.vue';

import batch from '@/api/batch/batchManagement';
import varietyManagement from '@/api/basicInformation/varietyManagement';
import facilityManagement from '@/api/digtalOperation/facilityManagement';
import batchDetail from '@/api/batch/batchDetail';

export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, BatchInfo, AddEdit },
  data() {
    return {
      title: '管理批次',
      batchInfoFlag:'',
      unfoldFlag: false,
      loading: false,
      addEditFlag: 'add',
      dialogVisible: false,
      isViewBatchInfo: false,
      formData: {},
      page: 1,
      size:10,
      selectIndex: 0,
      selectList: [],
      total: 10,
      parentId: '',
      batchType: 'MANAGEMENT',
      btnList: ['add', 'delete'],
      enumList: [{
        label: "新创建",
        type: 'CREATE'
      }, {
        label: "已称重",
        type: 'WEIGHED'
      },
      {
        label: "已投塘",
        type: 'PUT_POND'
      },
      {
        label: "已封塘",
        type: 'SEALED_POND'
      },
      {
        label: "已完成",
        type: 'COMPLETED'
      }],
      tableThead: [
        { isShow: true, label: '批次名称', prop: 'batchName', minWidth: '120px' },
        { isShow: true, label: '批次号', prop: 'batchCode', minWidth: '120px' },
        { isShow: true, label: '关联设施', slotName: 'facilityId' },
        { isShow: true, label: '初始养殖信息', slotName: 'objectives' },
        { isShow: true, label: '实际养殖信息', slotName: 'realities' },
        { isShow: true, label: '批次完成状态', slotName: 'status' }
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '300',
          cols: [
            {
              label: '完成',
              type: 'warning',
              flag: 'complete',
              handleRow: this.handleRow
            },
            {
              label: '编辑',
              type: 'primary',
              flag: 'edit',
              handleRow: this.handleRow
            },
            {
              label: '删除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      },
      id: 1000,
      batchInfo: [],
      searchFormData: {
        batchType: 'MANAGEMENT'
      },
      facilityObj: {},
      varietyList: [],
      facilityList: [],
      batchList: [],
      dataList: [],
      defaultProps: {
        children: 'batchList',
        label: 'batchName'
      },
      formItemList: [
        {
          label: '设施名称',
          type: 'select',
          selectOptions: [],
          param: 'facilityId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '批次名称',
          type: 'select',
          selectOptions: [],
          param: 'batchId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
    }
  },
  mounted() {
    this.initData();
    this.queryPageByCondition();
  },
  methods: {
    async initData() {
      // 获取批次列表 
      batch.queryByCondition({ batchType: 'MANAGEMENT' }).then(res => {
        this.batchList = res.data
      })
      //获取品种；
      let { data: varietyList } = await varietyManagement.queryByCondition({})
      this.varietyList = varietyList || [];
      //获取养殖设施；
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      this.facilityList = facilityList || [];
      this.facilityObj = {}
      facilityList.forEach(item => {
        this.facilityObj[item.facilityId] = item.facilityName
      })
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('facilityId') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchId') !== -1) {
          let selectOptions = this.batchList.map(data => {
            return {
              text: data.batchName, value: data.batchId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'staffName') {
          let selectOptions = this.person.map(data => {
            return {
              text: data.person.name, value: data.person.name
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    queryPageByCondition() {
      console.log(this.searchFormData)
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData,
          batchType: this.batchType
        }
      };
      batch.queryPageByCondition(params).then(res => {
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      });
    },
    search(data) {
      this.page = 1;
      this.searchFormData = { ...this.searchFormData, ...data };
      this.queryPageByCondition();
    },
    delList(deleteList = [], key = 'batchId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      if (list.length == 0) return
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await batch.delList(list);
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    selectionChange(val) {
      this.selectList = val
    },
    // 操作方法
    handleRow(rowData, item) {
      console.log(rowData, item);
      this.parentId = rowData.parentId;
      this.addEditFlag = item.flag
      if (item.flag == 'delete') {
        this.delList([rowData])
      } else if (item.flag == 'edit') {
        if (rowData.status == 'COMPLETED') {
          this.$message.warning('该批次已完成')
        } else {
          this.editPond(rowData)
        }
      } else if (item.flag == 'complete') {
        if (rowData.status == 'COMPLETED') {
          this.$message.warning('该批次已完成')
        } else {
          this.finish(rowData.batchId)
        }
      }
    },

    finish(id) {
      this.$confirm('你确定要完成该批次?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batch.completeBatch(id).then(res => {
          if (res.code == 1) {
            this.$message.success('操作成功!');
            this.queryPageByCondition();
          } else {
            this.$message.warning(res.msg || '操作失败!');
          }
        }).catch(err => {
          this.$message.warning(res.msg || '操作失败!');
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      this.selectIndex = enumInfo.index || 0;
      console.log(this.searchFormData)
      this.queryPageByCondition();
    },
    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.dialogVisible = true;
        this.batchType = 'MANAGEMENT';
        this.formData = {};
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择删除项')
        }
      }
      this.addEditFlag = flag
    },
    async queryByConditionBatchInfo(batchId,flag) {
      if (batchId) {
        let { data } = await batchDetail.queryByCondition({ batchId });
        this.batchInfo = data || [];
      } else {
        this.batchInfo = [];
      }
      this.batchInfoFlag = flag;
      this.isViewBatchInfo = true
    },
    async queryByConditionBatchPond(batchId,flag) {
      this.isActualData = true;
      if (batchId) {
        let { data } = await batch.queryAllByBatchId(batchId)
        this.batchInfo = data || [];
      } else {
        this.batchInfo = [];
      }
      this.batchInfoFlag = flag;
      this.isViewBatchInfo = true;
    },
    editPond(data) {
      this.parentId = data.parentId;
      this.batchType = data.batchType;
      this.addEditFlag = 'edit';
      this.formData = JSON.parse(JSON.stringify(data))
      this.dialogVisible = true
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.isViewBatchInfo = false;
      this.parentId = null;
      this.batchType = 'MANAGEMENT';
      this.queryPageByCondition();
      this.initData();
    },
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-tree-node__content {
  height: 50px;
  border-bottom: 1px solid #f0f0f0;
}

.custom-tree-container {
  width: 100%;

  .icon {
    font-size: 14px;
  }
}

::v-deep .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}

.label {
  padding-left: 10px;
}


.itemData {
  font-size: 14px;
  padding-left: 50px;
  color: #999999;
}
</style>